import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';
import { Observable, map } from 'rxjs';

export class ResOp<T = any> {
  @ApiProperty({ type: 'object' })
  data: T;

  @ApiProperty({ type: 'number', default: 0 })
  code: number;

  @ApiProperty({ type: 'string', default: '请求成功' })
  message: string;

  constructor(code: number, data: T, message = '请求成功') {
    this.code = code;
    this.data = data;
    this.message = message;
  }
}

@Injectable()
export class CustomReponseInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
    return next.handle().pipe(
      map((data) => {
        const { code, message, ...args } = data;
        return new ResOp(code || 0, args ?? null, message);
      }),
    );
  }
}
